import 'dart:async';
import 'dart:convert';

import 'package:card_swiper/card_swiper.dart';
import 'package:fast_gbk/fast_gbk.dart';
import 'package:flutter/material.dart';
import 'package:lyps_music/request/api.dart';
import 'package:lyps_music/store/index.dart';
import 'package:provider/provider.dart';

class MusicTextCard extends StatefulWidget {
  final String? textPath;
  const MusicTextCard({super.key, this.textPath});

  @override
  State<StatefulWidget> createState() => _MusicTextCardState();
}

class _MusicTextCardState extends State<MusicTextCard> {
  final SwiperController controller = SwiperController();
  String musicText = "";
  List<List<String>> musicTextArr = [];
  StreamSubscription<Duration>? handle;

  @override
  void initState() {
    super.initState();
    if (widget.textPath == null) return;
    Api.getMusicText(widget.textPath!).then((res) {
      String data = "";
      try {
        data = gbk.decode(res.data);
      } catch (err) {
        data = utf8.decode(res.data);
      }
      List<String> arr = data.split("\n");
      List<List<String>> textArr = [];
      var reg = RegExp(r'\[(.*?)\]\s*(.*)');
      for (var item in arr) {
        Match? match = reg.firstMatch(item);
        if (match != null) {
          var time = match.group(1);
          var text = match.group(2);
          if (time == null || time.isEmpty) continue;
          if (text == null || text.isEmpty) continue;
          textArr.add([time, text]);
        }
      }
      setState(() {
        musicTextArr = textArr;
      });
    });
    var player = context.read<Store>().audioplayer;
    handle = player.onPositionChanged.listen((data) {
      var currentTime = data.inMilliseconds;
      var i = musicTextArr.indexWhere((textarr) {
        var t_arr = textarr[0].split(':');
        var t = (int.parse(t_arr[0]) * 60 + double.parse(t_arr[1])) * 1000;
        if (currentTime <= t) return true;
        return false;
      });
      if (controller.index == i - 1) return;
      if (i != -1) {
        controller.index = i - 1;
        controller.move(i - 1);
      }
    });
  }

  @override
  void dispose() {
    if (handle != null) handle!.cancel();
    super.dispose();
  }

  Widget _noText() {
    return const Center(
      child: Text("暂无歌词",style: TextStyle(fontSize: 25,color: Colors.white),),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 400,
      margin: const EdgeInsets.only(top: 50),
      child: widget.textPath != null
          ? Swiper(
              controller: controller,
              itemCount: musicTextArr.length,
              viewportFraction: 0.15,
              loop: false,
              scrollDirection: Axis.vertical,
              itemBuilder: (context, index) {
                if (controller.index == index) {
                  return Text(
                    musicTextArr[index][1],
                    style: const TextStyle(color: Colors.green, fontSize: 20,fontWeight: FontWeight.bold),
                  );
                } else {
                  return Text(
                    musicTextArr[index][1],
                    style: const TextStyle(color: Colors.white),
                  );
                }
              },
            )
          : _noText(),
    );
  }
}
